//package com.jrx.anytxn.transaction.job.coupon.step;
// 
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.jrx.anytxn.common.constant.Constants;
//import com.jrx.anytxn.common.data.TxnRespCode;
//import com.jrx.anytxn.common.exception.TxnBizException;
//import com.jrx.anytxn.common.uitl.DateUtils;
//import com.jrx.anytxn.common.uitl.RedisUtils;
//import com.jrx.anytxn.common.uitl.StringUtils;
//import com.jrx.anytxn.customer.constant.CouponConstant;
//import com.jrx.anytxn.customer.constant.CustomerConstant;
//import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
//import com.jrx.anytxn.customer.entity.CmCustomerRightInfo;
//import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
//import com.jrx.anytxn.customer.entity.TlCouponDetail;
//import com.jrx.anytxn.customer.entity.TlRightsExchangeLog;
//import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerFirstLevelMapper;
//import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
//import com.jrx.anytxn.customer.service.IRightsExchangeLogService;
//import com.jrx.anytxn.customer.util.Md5Utils;
//import com.jrx.anytxn.feign.api.service.IUserApiService;
//import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
//import com.jrx.anytxn.feign.gateway.bean.Card;
//import com.jrx.anytxn.feign.gateway.request.CouponRequest05;
//import com.jrx.anytxn.feign.gateway.response.CouponResponse05;
//import com.jrx.anytxn.feign.gateway.service.IOuterGatewayService;
//import com.jrx.anytxn.number.exception.SegmentException;
//import com.jrx.anytxn.number.service.ISegmentService;
//import com.jrx.anytxn.param.constant.Constant;
//import com.jrx.anytxn.param.entity.PrActivityInfo;
//import com.jrx.anytxn.param.entity.PrRightsAndInterests;
//import com.jrx.anytxn.param.service.rights.IPrActivityInfoService;
//import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
//import com.jrx.anytxn.param.utils.ActivityUtils;
//import com.jrx.anytxn.transaction.config.CouponConfig;
//import com.jrx.anytxn.transaction.constant.TransBizConstant;
//import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
//import com.jrx.anytxn.transaction.job.coupon.dto.CustomerRightsDTO;
//import com.jrx.anytxn.transaction.service.ILoanMainInfoService;
//import com.jrx.anytxn.transaction.service.ISmsService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.batch.item.ItemProcessor;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.stereotype.Service;
//
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//import java.util.regex.Pattern;
//
///**
// * ClassName CouponSharingProcessor
// *
// * @author lujianyou zebin.zhang
// * @version 2.0
// * @description 分享消费送权益 processor
// * @date 2022/03/03 14:42
// **/
//@Service
//@Slf4j
//public class CouponSharingProcessor implements ItemProcessor<CmCustomerSecondLevel, CustomerRightsDTO> {
//
//    private static final String mobilePattern = "^[1]([3-9])[0-9]{9}$";
//    private static final String PREFIX_REDIS_KEY = "batch_mgm_";
//
//    @Autowired
//    private CouponConfig couponConfig;
//    @Autowired
//    private ILoanMainInfoService loanMainInfoService;
//    @Autowired
//    private IPrActivityInfoService activityInfoService;
//    @Autowired
//    private IPrRightsAndInterestsService rightsAndInterestsService;
//    @Autowired
//    private ExtCmCustomerSecondLevelMapper customerSecondLevelMapper;
//    @Autowired
//    private ISegmentService segmentService;
//    @Autowired
//    private IRightsExchangeLogService rightsExchangeLogService;
//    @Autowired
//    private IOuterGatewayService outerGatewayService;
//    @Autowired
//    private ExtCmCustomerFirstLevelMapper customerFirstLevelMapper;
//    @Autowired
//    private ISmsService smsService;
//    @Autowired
//    private IUserApiService userApiService;
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//
//    @Override
//    public CustomerRightsDTO process(CmCustomerSecondLevel item) throws Exception {
//
//        log.info("邀新用户消费送券 item:{}", JSONObject.toJSONString(item));
//
//        // 推荐人手机号码
//        String recommenderCode = item.getRecommenderCode();
//        String tenantId = item.getTenantId();
//
//        if (!checkRecommender(item)) {
//            return null;
//        }
//
//        // 推荐人是否激活心安花标识，默认激活
//        boolean recommenderActiveFlag = true;
//        // 被推荐人客户号
//        String recommendedCustomerId = item.getCustomerId();
//
//        String activityId = couponConfig.getActivity().getNewUserSharedConsumeFirstActivityId();
//        /**
//         * 1、推荐人列表 2、查看推荐人是否已发放此分享此人发放的优惠券 3、被推荐人是否有消费数据 4、发放优惠券并同时发送相关短信
//         */
//
//        // 根据手机号查询客户信息
//        CmCustomerSecondLevel cmCustomerSecondLevel = customerSecondLevelMapper.selectByChannelAndMobileAndTenantId(
//                Constants.DEFAULT_CHANNEL, recommenderCode, Constants.DEFAULT_TENANT_ID);
//        if (cmCustomerSecondLevel == null) {
//            recommenderActiveFlag = false;
//            log.info("根据租户号:{}、渠道号:{}、手机号:{}查询客户二级信息表，查无数据", Constants.DEFAULT_TENANT_ID, Constants.DEFAULT_CHANNEL,
//                    recommenderCode);
//        }
//
//        // 根据租户号、活动id、chargeAccount、被推荐人customerId
//        List<TlRightsExchangeLog> rightsExchangeLogList =
//                rightsExchangeLogService.listByChargeAccountAndRecommendedAndActivityId(tenantId, recommenderCode,
//                        recommendedCustomerId, activityId);
//        if (!rightsExchangeLogList.isEmpty()) {
//            log.info("邀新送券活动已派发,推荐人手机号码：{}、被推荐人：{}", recommenderCode, recommendedCustomerId);
//            return null;
//        }
//
//        // 查询被推荐人是有消费
//        List<AmLoanMainInfo> loanMainInfoList =
//                loanMainInfoService.listByCustomerIdAndLoanType(tenantId, recommendedCustomerId, "4");
//        if (loanMainInfoList.isEmpty()) {
//            log.info("被推荐人客户号:{}未有任何消费记录，不发权益。", recommendedCustomerId);
//            return null;
//        }
//
//        CustomerRightsDTO customerRightsDTO = new CustomerRightsDTO();
//        PrActivityInfo activityInfo = activityInfoService.getByTenantIdAndActivityId(tenantId, activityId);
//        String rightsId = activityInfo.getRightsId();
//        PrRightsAndInterests rightsAndInterests = rightsAndInterestsService.getByRightsId(tenantId, rightsId);
//
//        if (recommenderActiveFlag) {
//            CmCustomerFirstLevel cmCustomerFirstLevel =
//                    customerFirstLevelMapper.selectFirstLevelByOrgIdAndCusId(cmCustomerSecondLevel.getCustomerId(),
//                            cmCustomerSecondLevel.getOrganizationId(), item.getTenantId());
//            try {
//                TlRightsExchangeLog rightsExchangeLog = order(recommenderCode, rightsAndInterests,
//                        cmCustomerFirstLevel.getCustomerId(), cmCustomerFirstLevel.getChineseName(), recommendedCustomerId);
//                customerRightsDTO.setRightsExchangeLog(rightsExchangeLog);
//            } catch (TxnBizException e) {
//                log.info("下单异常：{}", e.getErrMsg());
//                return null;
//            }
//            CmCustomerRightInfo cmCustomerRightInfo =
//                    generateCustomerRightInfo(cmCustomerSecondLevel.getCustomerId(), activityInfo, rightsAndInterests);
//            TlCouponDetail couponDetail =
//                    generateCouponDetail(cmCustomerRightInfo, cmCustomerFirstLevel, recommendedCustomerId, recommenderCode);
//            customerRightsDTO.setCmCustomerRightInfo(cmCustomerRightInfo);
//
//            customerRightsDTO.setTlCouponDetail(couponDetail);
//        } else {
//            //尝试设置mgm缓存键值, 若不存在, 则缓存成功, 由另外一个分区进行if存在性校验(分区记录若存在, 则正常下单; 若不存在, else"兜底"逻辑处理)
//            //"兜底"逻辑: 推荐人记录在当前分区和其他分区都不存在, 则仅记录到ExchangeLog中, 然后发送短信
//            String rKey = PREFIX_REDIS_KEY + tenantId + recommendedCustomerId;
//            Boolean flag = redisTemplate.opsForValue().setIfAbsent(rKey, recommendedCustomerId);
//            if (flag != null) {
//                if (flag){
//                    redisTemplate.expire(rKey,5, TimeUnit.MINUTES);
//                    log.info("----往redis中插入一条数据：key:{} value:{}",rKey, recommendedCustomerId);
//                    return null;
//                }
//                try {
//                    TlRightsExchangeLog rightsExchangeLog =
//                            order(recommenderCode, rightsAndInterests, Constants.DEFAULT_CUSTOMER_ID, Constants.DEFAULT_CUSTOMER_NAME, recommendedCustomerId);
//                    customerRightsDTO.setRightsExchangeLog(rightsExchangeLog);
//                } catch (TxnBizException e) {
//                    log.info("下单异常：{}", e.getErrMsg());
//                    return null;
//                }
//            } else {
//                return null;
//            }
//        }
//        // 发送邀新短信
//        smsService.sendSmsMq(customerRightsDTO.getRightsExchangeLog(), TransBizConstant.SMS_TYPE_INVITE_NEW);
//        return customerRightsDTO;
//    }
//
//    /**
//     * 校验基本的参数
//     *
//     * @param item 客户二级信息表
//     * @return
//     */
//    private Boolean checkRecommender(CmCustomerSecondLevel item) {
//        String recommenderCode = item.getRecommenderCode();
//        String tenantId = item.getTenantId();
//        if (StringUtils.isBlank(recommenderCode)) {
//            return false;
//        }
//        if (!Pattern.matches(mobilePattern, recommenderCode)) {
//            log.info("推荐人编号:{} 不是手机号", recommenderCode);
//            return false;
//        }
//        if (recommenderCode.equals(item.getMobile())) {
//            log.info("被推荐人手机号不能和推荐人手机号一致,手机号：{}", recommenderCode);
//            return false;
//        }
//
//        Map<String, String> mapReq = new HashMap<>(8);
//        mapReq.put("tenantId", tenantId);
//        mapReq.put("channelNo", item.getChannel());
//        mapReq.put("mobileNo", recommenderCode);
//        ApiResponse<Boolean> response = userApiService.queryUserInfo(JSON.toJSONString(mapReq));
//        if (!response.getData()) {
//            log.info("推荐人手机号:{}未注册心安花", recommenderCode);
//            return false;
//        }
//
//        return true;
//    }
//
//    /**
//     * 权益平台下单
//     *
//     * @param mobile
//     * @param rightsAndInterests
//     * @param customerId
//     * @param chineseName
//     * @return
//     * @throws TxnBizException
//     */
//    private TlRightsExchangeLog order(String mobile, PrRightsAndInterests rightsAndInterests, String customerId,
//                                      String chineseName, String recommendedCustomerId) throws TxnBizException {
//        // step2：下单京东E卡，获取卡密信息
//        String sceneOrderId = System.currentTimeMillis() + "";
//        String createCouponJson = generateCreateCouponReq(rightsAndInterests, mobile, sceneOrderId);
//        ApiResponse<CouponResponse05> couponResponse05ApiResponse = outerGatewayService.order(createCouponJson);
//
//        if (TxnRespCode.SUCCESS.getCode() != couponResponse05ApiResponse.getCode()) {
//            throw new TxnBizException(couponResponse05ApiResponse.getCode(), couponResponse05ApiResponse.getMessage());
//        }
//
//        CouponResponse05 couponResponse05 = couponResponse05ApiResponse.getData();
//        if (couponResponse05 == null || CustomerConstant.FAIL.equals(couponResponse05.getDealState())) {
//            throw new TxnBizException(Integer.valueOf(couponResponse05.getBusCode()), couponResponse05.getBusMsg());
//        }
//
//        // 写权益资格兑换日志表
//        return generateRightsExchangeLogOnCreatingSuccess(couponResponse05, customerId, chineseName, rightsAndInterests,
//                sceneOrderId, mobile, recommendedCustomerId);
//    }
//
//    /**
//     * 下单成功生产权益兑换流水记录
//     */
//    private TlRightsExchangeLog generateRightsExchangeLogOnCreatingSuccess(CouponResponse05 response05,
//                                                                           String customerId, String chineseName, PrRightsAndInterests rightsAndInterests, String sceneOrderId,
//                                                                           String mobile, String recommendedCustomerId) throws TxnBizException {
//        TlRightsExchangeLog rightsExchangeLog = new TlRightsExchangeLog();
//
//        try {
//            rightsExchangeLog.setId(segmentService.getId(CustomerConstant.TL_COUPON_DETAIL_INFO));
//        } catch (SegmentException e) {
//            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
//        }
//        rightsExchangeLog.setTenantId(rightsAndInterests.getTenantId());
//        rightsExchangeLog.setCustomerId(customerId);
//        rightsExchangeLog.setChineseName(chineseName);
//        rightsExchangeLog.setRightsId(rightsAndInterests.getRightsId());
//        rightsExchangeLog.setRightsType(rightsAndInterests.getRightsType());
//        rightsExchangeLog.setSceneId(CustomerConstant.SCENE_ID);
//        rightsExchangeLog.setSceneOrderId(sceneOrderId);
//        rightsExchangeLog.setCouponSystemOrderId(response05.getId());
//        rightsExchangeLog.setFingerprint(response05.getCustomerFingerprint());
//        rightsExchangeLog.setBuyQuantity((short) 1);
//        rightsExchangeLog.setCouponName(rightsAndInterests.getRightsName());
//        rightsExchangeLog.setUnitPrice(response05.getUnitPrice());
//        rightsExchangeLog.setTotalPrice(response05.getTotalPrice());
//        rightsExchangeLog.setOrderType(response05.getOrderType());
//        rightsExchangeLog.setCustomerFingerprint(response05.getCustomerFingerprint());
//        rightsExchangeLog.setCustomerPhone(response05.getCustomerPhone());
//        rightsExchangeLog.setChargeAccount(mobile);
//        rightsExchangeLog.setOrderState(response05.getOrderState());
//        rightsExchangeLog.setOrderCreateTime(DateUtils.parseDate(response05.getOrderCreateTime()));
//        rightsExchangeLog.setCreateTime(new Date());
//        rightsExchangeLog.setCreateBy(Constants.DEFAULT_USER);
//        rightsExchangeLog.setAppId("");
//        rightsExchangeLog.setChannel(Constants.DEFAULT_CHANNEL);
//        rightsExchangeLog.setLogoUrl(rightsAndInterests.getLogoUrl());
//        rightsExchangeLog.setResJson(JSON.toJSONString(response05));
//        rightsExchangeLog.setRecordVersionNumber(Constant.VERSION_NUMBER);
//        rightsExchangeLog.setActivityId(couponConfig.getActivity().getNewUserSharedConsumeFirstActivityId());
//        rightsExchangeLog.setRecommended(recommendedCustomerId);
//
//        List<Card> cardList = response05.getCards();
//        if (cardList != null && cardList.size() > 0) {
//            Card card = cardList.get(0);
//            rightsExchangeLog.setCardNo(card.getCardNo());
//            rightsExchangeLog.setCardPassword(card.getCardPassword());
//        }
//
//        return rightsExchangeLog;
//    }
//
//    /**
//     * 生成 2.5 下单请求字符串
//     *
//     * @param rightsAndInterests
//     * @param mobile
//     * @param sceneOrderId
//     * @return
//     */
//    private String generateCreateCouponReq(PrRightsAndInterests rightsAndInterests, String mobile,
//                                           String sceneOrderId) {
//        CouponRequest05 request = new CouponRequest05();
//        request.setMobile(mobile);
//        request.setFingerprint(Md5Utils.hash(mobile));
//        request.setCouponId(rightsAndInterests.getRightsId());
//        request.setBuyQuantity(1);
//        request.setChargeAccount(mobile);
//        request.setSceneOrderId(sceneOrderId);
//        return JSON.toJSONString(request);
//    }
//
//    private CmCustomerRightInfo generateCustomerRightInfo(String customerId, PrActivityInfo activityInfo,
//                                                          PrRightsAndInterests rightsAndInterests) throws TxnBizException {
//        CmCustomerRightInfo customerRightInfo = new CmCustomerRightInfo();
//
//        try {
//            customerRightInfo.setId(segmentService.getId(CustomerConstant.CM_CUSTOMER_RIGHT_INFO));
//        } catch (SegmentException segmentException) {
//            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
//        }
//        customerRightInfo.setRightsId(rightsAndInterests.getRightsId());
//        customerRightInfo.setTenantId(Constants.DEFAULT_TENANT_ID);
//        customerRightInfo.setChannel(Constants.DEFAULT_CHANNEL);
//        customerRightInfo.setCustomerId(customerId);
//        customerRightInfo.setOrganizationId(Constants.DEFAULT_ORG_NUMBER);
//        String rightsEffectivePeriod = activityInfo.getRightsEffectivePeriod();
//
//        customerRightInfo.setEffectDate(ActivityUtils.getEffectiveDateFrom(rightsEffectivePeriod,
//                DateUtils.parseDate(activityInfo.getEffectiveDate()), new Date()));
//        customerRightInfo.setExpiresDate(ActivityUtils.getExpireDateFrom(rightsEffectivePeriod,
//                DateUtils.parseDate(activityInfo.getExpireDate()), new Date()));
//        customerRightInfo.setRightsType(rightsAndInterests.getRightsType());
//        customerRightInfo.setRightsName(rightsAndInterests.getRightsName());
//
//        customerRightInfo.setLoanId("");
//        customerRightInfo.setAllowProducts(Constants.DEFAULT_PRODTCT_CODE);
//        // 因为先前已经兑换了，所以此处为已使用
//        customerRightInfo.setRightsStatus(CustomerConstant.RIGHTS_STATUS_1);
//
//        Date now = new Date();
//        customerRightInfo.setCreateTime(now);
//        customerRightInfo.setUpdateTime(now);
//        customerRightInfo.setUpdateBy(customerId);
//        customerRightInfo.setRecordVersionNumber(Constant.VERSION_NUMBER);
//        customerRightInfo.setActivityId(activityInfo.getActivityId());
//        customerRightInfo.setCouponCate("");
//        customerRightInfo.setRightsQuantity(1);
//        customerRightInfo.setProductCode(Constants.DEFAULT_PRODTCT_CODE);
//        customerRightInfo.setCycleUse(CouponConstant.CYCLE_USE_N);
//
//        return customerRightInfo;
//    }
//
//    private TlCouponDetail generateCouponDetail(CmCustomerRightInfo customerRightInfo,
//                                                CmCustomerFirstLevel cmCustomerFirstLevel, String recommendedCustomerId, String mobile) throws TxnBizException {
//        TlCouponDetail tlCouponDetail = new TlCouponDetail();
//        String customerId = customerRightInfo.getCustomerId();
//        try {
//            tlCouponDetail.setId(segmentService.getId(CustomerConstant.TL_COUPON_DETAIL_INFO));
//        } catch (SegmentException segmentException) {
//            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
//        }
//        tlCouponDetail.setTenantId(Constants.DEFAULT_TENANT_ID);
//        tlCouponDetail.setOrganizationId(TransBizConstant.DEFAULT_ORG_ID);
//        tlCouponDetail.setChannel(Constants.DEFAULT_CHANNEL);
//        tlCouponDetail.setCustomerId(customerId);
//        tlCouponDetail.setRecommended(recommendedCustomerId);
//
//        tlCouponDetail.setRightsId(customerRightInfo.getRightsId());
//        tlCouponDetail.setRightsName(customerRightInfo.getRightsName());
//        tlCouponDetail.setRightsType(customerRightInfo.getRightsType());
//        tlCouponDetail.setCustomerRightsId(customerRightInfo.getId());
//        tlCouponDetail.setCouponSummaryId(0L);
//
//        tlCouponDetail.setChineseName(cmCustomerFirstLevel.getChineseName());
//        tlCouponDetail.setIdNumber(cmCustomerFirstLevel.getIdNumber());
//        tlCouponDetail.setMobile(mobile);
//
//        Date now = new Date();
//        tlCouponDetail.setCreateTime(now);
//        tlCouponDetail.setUpdateTime(now);
//        tlCouponDetail.setUpdateBy(customerId);
//        tlCouponDetail.setRecordVersionNumber(Constant.VERSION_NUMBER);
//        tlCouponDetail.setActivityId(customerRightInfo.getActivityId());
//
//        return tlCouponDetail;
//    }
//
//}
